import random
import time

import requests
from pyquery import PyQuery as py
from xlsxwriter import Workbook

header = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-encoding": "gzip, deflate, br",
    "accept-language": "zh-CN,zh;q=0.9",
    "cache-control": "max-age=0",
    "if-modified-since": "Tue, 09 Nov 2021 13:28:26 GMT",
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "none",
    "sec-fetch-user": "1",
    "upgrade-insecure-requests": "1",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
}
url = 'https://www.kugou.com/yy/rank/home/3-6666.html?from=rank'


def getHtml(url):
    response = requests.get(url)
    if response.status_code == requests.codes.ok:
        html = response.content.decode("utf-8")
        # with open("kugou.html", "w", encoding="utf-8") as fp:
        #     fp.write(html)
        return html

# with open("kugou.html", "r", encoding="utf-8") as fp:
#     html = fp.read()


def parseHtml(html):
    doc = py(html)
    lis = doc("#rankWrap ul>li")
    for li in lis.items():
        info = li.attr("title")
        info: str
        info = info.split(" - ")
        yield {
            "singer": info[0],
            "song": info[1],
            "rank": li(".pc_temp_num").html().strip(),
            "time": li(".pc_temp_time").html().strip()
        }


urls = ["https://www.kugou.com/yy/rank/home/{}-6666.html?from=rank".format(str(page)) for page in range(1, 6)]


def exec():
    header = ["排名", "歌曲", "歌手", "播放时间"];
    work_book = Workbook("酷狗飙升榜.xls")
    sheet = work_book.add_worksheet("酷狗飙升榜")
    row_index = 0
    for col_index, col_val in enumerate(header):
        sheet.write(row_index, col_index, col_val)
    row_index = row_index + 1
    for url in urls:
        html = getHtml(url)
        for item in parseHtml(html):
            sheet.write(row_index, 0, item['rank'])
            sheet.write(row_index, 1, item['song'])
            sheet.write(row_index, 2, item['singer'])
            sheet.write(row_index, 3, item['time'])
            row_index = row_index + 1
        time.sleep(random.randint(0, 3))
    work_book.close()


exec()
